from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware

from app.utils.middlewares import get_userinfo
from app.settings.config import appConf

from app.routers.test import items

from app.sqlModels import create_sql_model



app = None


class CreateApp():
    def __init__(self):
        self.__app = None


    def __CrossDomain(self):
        """
        跨越设置
        :return: bool
        """
        try:
            self.__app.add_middleware(
                CORSMiddleware,
                allow_origins=appConf["ORIGINS"],
                allow_credentials=True,
                allow_methods=["*"],
                allow_headers=["*"],
            )
        except Exception as e:
            return False
        return True

        pass



    def __RegisterRouters(self):

        self.__app.include_router(items.router)
        pass


    def __RegisterMiddleware(self):
        self.__app.add_middleware(BaseHTTPMiddleware, dispatch=get_userinfo)

        pass

    def __connect_db(self):

        create_sql_model()


    def create_app(self):

        self.__app =FastAPI(
            root_path="/fastapi-test"
        )
        self.__app

        # 迁移数据库
        self.__connect_db()
        # 跨域设置
        self.__CrossDomain()
        # 注册路由
        self.__RegisterRouters()
        # 注册中间件
        self.__RegisterMiddleware()

        return self.__app






app = CreateApp().create_app()